package cn.org.donald.framework.util;

import com.auth0.jwt.interfaces.DecodedJWT;
import cn.org.donald.framework.constant.EncodeConstant;
import cn.org.donald.framework.pojo.dto.SmsVerifyDto;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 *  加密工具类
 * @author : Donald
 * @since : 2020/11/10 16:42
 */
public class EncodeUtil {

    /**
     * 获取随机盐
     * @return String
     */
    public static String getSalt(){
        StringBuilder stringBuffer = new StringBuilder();
        for (int i = 0; i < EncodeConstant.SALT_NUM ; i++){
            char aChar = EncodeConstant.SALT_CHAR[new Random().nextInt(EncodeConstant.SALT_CHAR.length)];
            stringBuffer.append(aChar);
        }
        return stringBuffer.toString();
    }

    /**
     * 获取加密后的密码
     * @return String
     */
    public static String getEncodePassword(String password,String saltValue){
        /*
         * 参数1 密码
         * 参数2 加盐值
         * 参数3 散列次数
         */
        Md5Hash md5Hash = new Md5Hash(password, saltValue, EncodeConstant.HASH_ITERATIONS);
        return md5Hash.toHex();
    }

    /**
     * 验证手机验证码
     * @param smsVerifyDto
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    public static boolean verifySms(SmsVerifyDto smsVerifyDto, HttpServletRequest request) {
        try {
            DecodedJWT verify = JwtUtil.verify(smsVerifyDto.getVerifyToken());
            String userIdFromToken = verify.getClaim("userId").asString();
            if (userIdFromToken.equals(RequestUtil.getUserId(request).toString())){
                Object o = redisTemplate().opsForValue().get(smsVerifyDto.getVerifyToken());
                assert o != null;
                String codeFromRedis =  o.toString();
                if (codeFromRedis != null && codeFromRedis.equals(smsVerifyDto.getVerifyCode())){
                    Boolean delete = redisTemplate().delete(smsVerifyDto.getVerifyToken());
                    return delete != null && delete;
                }
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return false;
    }

    private static RedisTemplate redisTemplate(){
        return (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
    }
}
